package com.lizemin.bank.controller;

import com.lizemin.bank.common.RespBean;
import com.lizemin.bank.constants.Constants;
import com.lizemin.bank.entity.User;
import com.lizemin.bank.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Objects;


/**
 * @author lzm
 * @date 2025/4/10 20:55
 * @description
 */
@Slf4j
@RestController
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    HttpSession session;

    @Autowired
    HttpServletRequest request;

    @GetMapping("/login")
    public RespBean login(String username, String password) {
        log.info("用户名：{}，密码：{}", username, password);
        User user = userService.findUserByUsername(username);
        if (Objects.isNull(user)) {
            throw new RuntimeException("用户不存在");
        }
        if (!Objects.equals(user.getPassword(), password)) {
            throw new RuntimeException("密码错误");
        }
        // 存储用户的登录状态
        session.setAttribute(Constants.LOGIN_STATUS, user);
        String oldSessionId = session.getId();
        // 修改sessionId，防止会话固定攻击
        String newSessionId = request.changeSessionId();
        log.info("sessionId从{}变成了{}", oldSessionId,newSessionId);
        log.info("用户{}登录成功", username);
        return RespBean.success();
    }

    @GetMapping("/logout")
    public RespBean logout() {
        session.invalidate();
        return RespBean.success();
    }

    @GetMapping("/transfer")
    public RespBean transfer(String targetUser, Integer balance) {
        User user = (User) session.getAttribute(Constants.LOGIN_STATUS);
        if (Objects.isNull(user)) {
            throw new RuntimeException("用户未登录");
        }
        log.info("已经将【{}】账户中的钱转给【{}】, 转账金额：{}", user.getUsername(), targetUser, balance);
        return RespBean.success("转账成功");
    }


}
